package com.yz.dataStructure;

public class SparseArray {
    public static void main(String[] args) {
        //将一个二维数组转换成稀疏矩阵
        //1.定义一个11 * 11 的二维数组
        //2.结果1默认是白子  2默认是黑子
        int[][] ints = new int[11][11];
        ints[1][2] = 1;
        ints[2][3] = 2;
        int count = 0;
        System.out.println("原始的二维数组：");
        for (int[] anInt : ints) {
            for (int data : anInt) {
                if (data != 0){
                    count++;
                }
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }
        //System.out.println(count);

        //将二维数组装换成稀疏矩阵
        int[][] sparse = new int[count+1][count+1];
        //第一行放二维矩阵的一些信息，横行数据以及非零数
        sparse[0][0] = ints.length;
        sparse[0][1] = ints.length;
        sparse[0][2] = count;

        int sun = 0;
        for (int i = 0; i < ints.length; i++) {
            for (int j = 0; j < ints.length; j++) {
                //这里的ij对应着二维数组的行和列
                if (ints[i][j] != 0){
                    sun++;
                    sparse[sun][0] = i;
                    sparse[sun][1] = j;
                    sparse[sun][2] = ints[i][j];
                }
            }
        }

        System.out.println("稀疏数组:");
        //数据输入完毕后，打印这个稀疏数组
        for (int[] ints1 : sparse) {
            for (int i : ints1) {
                System.out.printf("%d\t",i);
            }
            System.out.println();
        }


        //再将这个稀疏数组转换成二维数组
        int[][] Array = new int[sparse[0][0]][sparse[0][1]];
        System.out.println("还原后：");
        for (int i = 1; i < sparse.length; i++) {
                Array[sparse[i][0]][sparse[i][1]] =sparse[i][2];
        }

        for (int[] ints1 : Array) {
            for (int i : ints1) {
                System.out.printf("%d\t",i);
            }
            System.out.println();
        }


    }
}
